// pages/bookingGoods/confirm/index.js
var app = getApp()
var call = require("../../../utils/request.js");
Page({
  data: {
    pageStatus: false,
    userInfo: {},
    timeStatus: true, // 上架时间状态
    priceStatus: true, // 价格状态
    hide_good_box: true,
    total: 0, // 合计
    calculation: 0, // 用作计算的合计
    selectedData: [], // 已选产品
    address: '', // 地址
    addressIndex: 0,
    address_id: 0, // 地址Id
    addressData: [], // 地址数据
    paymentMethod: '', // 支付方式
    pay_type: 0, // 支付方式:1=余额，2=微信
    paymentMethodData: [{ id: 1,name: '余额' },{ id: 2,name: '微信' }], // 支付方式数据

    // 新增
    timeData: ['09:00 -12:00', '13:00 -18:00'],
    items: [
      {title: '余额',value: 1,checked: 'true'},
      {title: '微信',value: 2,},
    ],
    paytype: 1, // 支付方式
    vipStatus: false,
    source: 1, // 1=系统添加,2=用户添加
    distributionFee: 0, // 配送费用
    remarks: '', // 普通用户备注

    showAddress: false, // 地址选择
  },
    
  onLoad: function (options) {
    this.isVip() // 是否是vip
    this.getDefaultAddress() //获取收货地址-是否有默认
    let selectedData = wx.getStorageSync('bookingGoodsData');
    let userInfo = wx.getStorageSync('userInfo');
    for(let item of selectedData){
      item.reekoDate = item.delivery_time
      item.reekoTime = '09:00 -12:00'
      
    }
    this.setData({ userInfo,total: options.total,selectedData,calculation: options.total })
    console.log(userInfo)

    this.getRemarks() // 获取备注
  },
  // 打开选择地址
  openAddress () {
    this.setData({ showAddress: true })
  },
  // 关闭
  onCloseAddress () {
    this.setData({ showAddress: false })
  },
  // 选择改变后
  onChangeAddress(event) {
    const { picker, value, index } = event.detail;
    this.setData({ addressIndex: index })
  },
  // 获取备注
  getRemarks () {
    let {mobile} = wx.getStorageSync('userInfo');
    call.getData('/api/book_order/latestOrder', {
      mobile,
    },
    data => {
      if(data.code == 1){
        if(data.data){
          this.setData({ remarks: data.data.remarks })
        }
      }else{
        wx.showToast({ icon: 'none',title: data.msg })
      }
      this.setData({ pageStatus: true })
    },
    err => {
      console.log(err)
    },false)
  },
  // vip地址
  goAddressVip () {
    wx.navigateTo({
      url: '/pages/bookingGoods/addressVip/index/index'
    })
  },
  // 普通用户备注
  bindKeyInput: function (e) {
    this.setData({
      remarks: e.detail.value
    })
  },
  // 获取默认地址
  getDefaultAddress () {
    call.getData('/api/book_order/address', {},
    data => {
      if(data.code == 1){
        for(let [index,list] of data.data.entries()){
          if(list.isdefault == 1){
            let address = list.address;
            let address_id = list.id;
            let source = list.source;
            this.setData({
              address,
              address_id,
              source,
              addressIndex: index
            })
            if(list.source == 2){
              this.getDistributionFee() // 获取配送费
            }else{
              this.changTotal() // 改变合计
            }
          }
        }
        this.setData({addressData: data.data})
        console.log(data)
      }else{
        wx.showToast({ icon: 'none',title: data.msg })
      }
    },
    err => {
      console.log(err)
    },false)
  },
  // 获取收货地址
  getAddress () {
    call.getData('/api/book_order/address', {},
    data => {
      if(data.code == 1){
        this.setData({addressData: data.data})
        console.log(data)
      }else{
        wx.showToast({ icon: 'none',title: data.msg })
      }
    },
    err => {
      console.log(err)
    },false)
  },
  // 提交订单
  goSettlement () {
    let goods = this.data.selectedData.map(item => {
      return {
        goods_id: item.id,
        goods_name: item.goods_name,
        unit_price: item.sell_price,
        num: item.num,
        total_price: item.total,
        delivery_time: item.delivery_time,
        //remarks: item.reekoTime
      }
    })
    if(this.data.address){
      if(this.data.paytype){
        wx.showLoading({
          mask: true,
          title: '支付中...',
        });
        let Data = this.data;
        let address = Data.address;
        let address_id = Data.address_id;
        let source = Data.source;
        let username = Data.userInfo.username;
        let mobile = Data.userInfo.mobile;
        let amount = Data.total;
        let pay_type = Data.paytype;
        let remarks = Data.remarks;
        
        call.request('/api/book_order/create', { 
          address,
          address_id,
          source,
          username,
          mobile,
          amount,
          pay_type,
          goods: goods,
          remarks
         },
        data => {
          if(data.code == 1){
            if(pay_type == 1){
              wx.removeStorageSync('bookingGoodsData')
              wx.reLaunch({
                url: '/pages/bookingGoods/success/index'
              })
            }else{
              let order_id = data.data.order_id;
              call.getData('/api/book_order/pay', { order_id },
              res => {
                if(res.code == 1){
                  let { timeStamp,nonceStr,signType,paySign } = res.data;
                  wx.requestPayment({
                    timeStamp,
                    nonceStr,
                    package: res.data.package,
                    signType,
                    paySign,
                    success (res) {
                      wx.removeStorageSync('bookingGoodsData')
                      wx.reLaunch({
                        url: '/pages/bookingGoods/success/index'
                      })
                    },
                    fail (res) {
                      wx.hideLoading();
                    }
                  })
                }else{
                  wx.showToast({ icon: 'none',title: res.msg })
                }
              },
              err => {
                console.log(err)
              },false)
            }
          }else{
            wx.showToast({ icon: 'none',title: data.msg })
          }
        }, err =>{
          console.log(err)
        },false,"application/json; charset=utf-8")
      }else{
        wx.showToast({ icon: 'none',title: '请选择支付方式' })
      }
    }else{
      wx.showToast({ icon: 'none',title: '请选择收货地址' })
    }
  },
  // 选择收货地址
  addressChange () {
    let index = this.data.addressIndex;
    let address = this.data.addressData[index].address;
    let address_id = this.data.addressData[index].id;
    let source = this.data.addressData[index].source;
    this.setData({
      address,
      address_id,
      source,
      showAddress: false
    })
    if(source == 2){
      this.getDistributionFee() // 获取配送费
    }else{
      this.changTotal() // 改变合计
    }
  },
  // 获取配送费
  getDistributionFee () {
    call.getData('/api/book_order/freight', {},
    res => {
      if(res.code == 1){
        let distributionFee = res.data.fee
        this.setData({ distributionFee })
        this.changTotal() // 改变合计
      }else{
        wx.showToast({ icon: 'none',title: res.msg })
      }
    },
    err => {
      console.log(err)
    },false)
  },
  // 改变合计
  changTotal(){
    let total = this.data.total
    if(this.data.source == 1){
      total = Number(this.data.calculation)
    }else{
      total = Number(this.data.calculation) + Number(this.data.distributionFee)
      
    }
     
    console.log(total)
    this.setData({ total: Math.round(total*100)/100 })
  },
  // 选择配送日期
  distributionDataChange (e) {
    let index = e.currentTarget.dataset.index;
    console.log(e.detail.value,)
    let selectedData = this.data.selectedData;
    selectedData[index].delivery_time = e.detail.value;
    this.setData({
      selectedData
    })
  },
  // 选择配送时间
  distributionTimeChange (e) {
    let index = e.currentTarget.dataset.index;
    console.log(e.detail.value,)
    let selectedData = this.data.selectedData;
    selectedData[index].reekoTime = this.data.timeData[e.detail.value];
    this.setData({
      selectedData
    })
  },
  // 选择支付方式
  // 支付方式改变
  radioChange(e) {
    this.setData({ paytype: e.detail.value })
    console.log('radio发生change事件，携带value值为：', e.detail.value)
  },
  // 返回上一页
  goReturn: function () {
    let pages = getCurrentPages(); //获取当前页面js里面的pages里的所有信息。
    let prevPage = pages[pages.length - 2]; 
    wx.navigateBack({
      delta: 1
    })
  },
  // 是否是vip
  isVip () {
    call.getData('/api/ship_address/vip', {},
    data => {
      if(data.code == 1){
        this.setData({ vipStatus: data.data })
        console.log(data)
      }else{
        wx.showToast({ icon: 'none',title: data.msg })
      }
    },
    err => {
      console.log(err)
    },false)
  },
})